﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;
using NetBay.Core.BusinessEntities;
using NetBay.Core.Silverlight.Log;

using Rio.Applications.Web.Services;
using Rio.Framework.Localisation;
using Rio.Framework.Pages;
using Rio.Framework.Pages.AppCode.Enums;
using Rio.Framework.Pages.Context;
using Rio.Framework.Pages.Events;
using Rio.Framework.Pages.Viewer;

using Telerik.Windows.Controls;
using Rio.Framework.Pages.Controls;
using Rio.Framework.Pages.AppCode.Models;
using Rio.Framework.Pages.ChildWindows;

namespace Rio.Application.RioWeb.Flow.Controls
{
    /// <summary>
    /// This class manage all actions of the flow viewer
    /// </summary>
    public partial class DisplayPage : UserControl
    {
        #region Fields

        public List<long> m_oGroupIdList;
        public List<long> m_sDocumentIdList;
        public List<Document> m_sDocumentList;
        public List<string> m_sDocuments;

        private SelectModeDocument DisplayMode;
        private Document m_oCurrentDocument;
        private ListViewer m_oListViewer;
        private ListVignetteSearch m_oListVignetteSearch;
        private SplashScreen m_oSplashScreen = new SplashScreen();
        private UCViewer m_oViewerControl;
        private string m_sLabelAuthor;
        private string m_sLabelNoHistory;
        private string m_sLabelNote;
        private string m_sLabelNumChrono;
        private string m_sMsgIndexedBy;
        private string m_sMsgIndexOK;
        private string m_sMsgReadBy;
        private string m_sMsgRejectedBy;
        private string m_sMsgRejectOK;
        private string m_sMsgRemindBy;
        private string m_sMsgRemindOK;
        private string m_sMsgToValidate;
        private string m_sMsgTransferedBy;
        private string m_sMsgTransferOK;
        private string m_sMsgValidatedBy;
        private string m_sMsgValidateOK;

        private FlowIndexPanel flowIndexPanel;

        #endregion Fields

        #region Constructors

        /// <summary>
        /// STEP-1
        /// DisplayPage Constructor
        /// </summary>
        /// <param name="P_cMsg"></param>
        public DisplayPage(MessageFlowDisp P_cMsg)
        {
            m_oSplashScreen.Show();
            Rio.Framework.Pages.ModalControls.ModalDialogController.Launch(m_oSplashScreen);
            m_Message = P_cMsg;
            InitializeComponent();
            //Initialize labels
            InitLabel();
            DataContext = m_Message;
            
            LoadMessageFlowDocument(true);
            buttonIndexer.IsEnabled = GlobalWebContext.GetUserCanImport();
        }

        #endregion Constructors

        #region Enumerations

        private enum StateDoc
        {
            New = 0, Read, Indexed, Validated, Tranfered, Rejected, Done, Remind
        }

        enum SelectModeDocument
        {
            Thumbnail,
            Viewer,
            List
        }

        #endregion Enumerations

        #region Events

        public event EventHandler DataHasChanged;

        #endregion Events

        #region Properties

        public Document CurrentDocument
        {
            get { return m_oCurrentDocument; }
            set
            {
                m_oCurrentDocument = value;
            }
        }

        public MessageFlowDisp m_Message
        {
            get;
            set;
        }

        #endregion Properties

        #region Methods

        public void LoadMessageFlowDocument(bool p_bInit = false)
        {
            BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
            var query = l_oBEDomainContext.GetDocumentByMessageFlowQuery(m_Message.Identifier);
            l_oBEDomainContext.Load(query, OnGetDocumentByMessageFlowQuery, p_bInit); 
        }


        /// <summary>
        /// Manages the toolbar and context menu.
        /// </summary>
        private void ManageToolbarAndContextMenu()
        {
            FolderType currentFolderType = GlobalWebContext.CurrentUser.GroupList.SelectMany(g => g.OrganizationList).SelectMany(o => o.FolderTypesList).Where(ft => ft.Identifier == CurrentDocument.FolderTypeIdentifier).FirstOrDefault();
           
            Organization currentOrganization = GlobalWebContext.CurrentUser.GroupList.SelectMany(g => g.OrganizationList).Where(o => currentFolderType != null && o.Identifier == currentFolderType.Identifier).FirstOrDefault();

            switch (DisplayMode)
            {
                case SelectModeDocument.Thumbnail:
                    ((DocumentRibbonBar)m_oListVignetteSearch.FindName("DocumentToolbar")).ManageToolbar();
                    ((DocumentContextMenu)m_oListVignetteSearch.FindName("DocumentContextMenu")).ManageContextMenuItemState();

                    ((DocumentRibbonBar) m_oListVignetteSearch.FindName("DocumentToolbar")).SetUserPriviledges(currentFolderType, currentOrganization);
                    ((DocumentContextMenu)m_oListVignetteSearch.FindName("DocumentContextMenu")).SetUserPriviledges(currentFolderType, currentOrganization);
                    break;
                case SelectModeDocument.Viewer:
                    ((DocumentRibbonBar)m_oViewerControl.FindName("DocumentToolbar")).ManageToolbar();
                    ((DocumentContextMenu)m_oViewerControl.FindName("DocumentContextMenu")).ManageContextMenuItemState();
                    
                    ((DocumentRibbonBar) m_oViewerControl.FindName("DocumentToolbar")).SetUserPriviledges(currentFolderType, currentOrganization);
                    ((DocumentContextMenu) m_oViewerControl.FindName("DocumentContextMenu")).SetUserPriviledges(currentFolderType, currentOrganization);
                    break;
                case SelectModeDocument.List:
                    ((DocumentRibbonBar)m_oListViewer.FindName("DocumentToolbar")).ManageToolbar();
                    ((DocumentContextMenu)m_oListViewer.FindName("DocumentContextMenu")).ManageContextMenuItemState();
                    
                    ((DocumentRibbonBar) m_oListViewer.FindName("DocumentToolbar")).SetUserPriviledges(currentFolderType, currentOrganization);
                    ((DocumentContextMenu)m_oListViewer.FindName("DocumentContextMenu")).SetUserPriviledges(currentFolderType, currentOrganization);
                    break;
            }
        }

        public virtual void OnDataHasChanged()
        {
            if (DataHasChanged != null)
                DataHasChanged(this, EventArgs.Empty);
        }

        /// <summary>
        /// /// STEP-2
        /// </summary>
        /// <param name="result"></param>
        public void OnGetDocumentByMessageFlowQuery(LoadOperation<Document> result)
        {
            m_sDocumentList = new List<Document>(result.Entities);

            if ((m_oCurrentDocument == null) && (m_sDocumentList.Count > 0))
            {
                CurrentDocument = m_sDocumentList.First();
                m_sDocuments = new List<string>();
                m_sDocumentIdList = new List<long>();
                foreach (Document l_oDoc in m_sDocumentList)
                {
                    string l_sFullPath = System.IO.Path.Combine(l_oDoc.RelativePath, l_oDoc.ImageName);
                    m_sDocuments.Add(l_sFullPath);
                    m_sDocumentIdList.Add(l_oDoc.Identifier);
                }

                //Set the message as "Read"
                SetAsRead();

                if (m_oViewerControl == null)
                {
                    InitListThumbnailsAndViewerControl(m_sDocumentList);
                }
                else
                {
                    m_oViewerControl.ListDocument = m_sDocumentList;
                    m_oViewerControl.ListAllDocFileName = m_sDocuments;
                    m_oListVignetteSearch.ListDocument = m_sDocumentList;
                }
            }
        }

        /// <summary> 
        /// Enable to load the State History in the right panel 
        /// </summary>
        /// <param name="result"></param>
        public void OnHistoryByGroupMessageFlowQuery(LoadOperation<StateMessageFlow> p_oResult)
        {
            try
            {
                List<StateMessageFlow> l_oReturnObjects = new List<StateMessageFlow>(p_oResult.Entities);
                if (l_oReturnObjects != null && l_oReturnObjects.Count > 0)
                {
                    StateMessageFlow l_oReturnObject = l_oReturnObjects.First();

                    if (l_oReturnObject.IsValid == true)
                    {
                        StateHistory.Text = string.Empty;
                        foreach (StateMessageFlow l_oStateMsg in l_oReturnObjects)
                        {
                            string l_sUserInfo = l_oStateMsg.FirstName + " " + l_oStateMsg.LastName;
                            long caseSwitch = l_oStateMsg.StateId;
                            switch (caseSwitch)
                            {
                                case (long)StateDoc.Validated:
                                    StateHistory.Text += String.Format(m_sMsgValidatedBy, l_oStateMsg.DateAdded, "\r", l_sUserInfo) + "\r\r";
                                    buttonRefuser.IsEnabled = false;
                                    buttonValider.IsEnabled = false;
                                    break;
                                case (long)StateDoc.Rejected:
                                    StateHistory.Text += String.Format(m_sMsgRejectedBy, l_oStateMsg.DateAdded, "\r", l_sUserInfo);
                                    if (l_oStateMsg.Comment != null)
                                    {
                                        StateHistory.Text += "\r------------ \r" + l_oStateMsg.Comment + "\r" + "------------ \r\r";
                                    }
                                    else
                                    {
                                        StateHistory.Text += "\r\r";
                                    }
                                    buttonRefuser.IsEnabled = false;
                                    buttonValider.IsEnabled = false;
                                    buttonIndexer.IsEnabled = false;
                                    break;
                                case (long)StateDoc.Indexed:
                                    StateHistory.Text += String.Format(m_sMsgIndexedBy, l_oStateMsg.DateAdded, "\r", l_sUserInfo) + "\r\r";
                                    buttonRefuser.IsEnabled = false;
                                    break;
                                case (long)StateDoc.Read:
                                    StateHistory.Text += String.Format(m_sMsgReadBy, l_oStateMsg.DateAdded, "\r", l_sUserInfo) + "\r\r";
                                    break;
                                case (long)StateDoc.Tranfered:
                                    StateHistory.Text += String.Format(m_sMsgTransferedBy, l_oStateMsg.DateAdded, "\r", l_sUserInfo);
                                    if (l_oStateMsg.Comment != null)
                                    {
                                        StateHistory.Text += "\r------------ \r" + l_oStateMsg.Comment + "\r" + "------------ \r\r";
                                    }
                                    else
                                    {
                                        StateHistory.Text += "\r\r";
                                    }
                                    buttonRefuser.IsEnabled = false;
                                    break;
                                case (long)StateDoc.Remind:
                                    StateHistory.Text += String.Format(m_sMsgRemindBy, l_oStateMsg.DateAdded, "\r", l_sUserInfo) + "\r\r";
                                    break;
                            }
                        }
                    }
                    else
                    {
                        MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, "", MessageBoxButtons.Ok, MessageBoxIcon.Error);
                        L_oMessage.Show();
                    }
                }
                else
                {
                    StateHistory.Text = string.Empty + m_sLabelNoHistory;
                }
            }
            catch (Exception ex)
            {
                MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, "----OnHistoryByGroupMessageFlowQuery: " + ex.Message, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                L_oMessage.Show();
            }
        }

        public void OnUpdateMessageFlowLastReadDateQuery(LoadOperation<ReturnObject> p_oResult)
        {
            //Nothing to do
        }

        /// <summary>
        /// Enable to load the viewer with the image selected 
        /// </summary>
        /// <param name="result"></param>
        public void OnUpdateStateDocListQueryCallback(LoadOperation<ReturnObject> p_oResult)
        {
            List<ReturnObject> l_oReturnObjects = new List<ReturnObject>(p_oResult.Entities);
            if (l_oReturnObjects != null)
            {

                int l_iStateId = (int)p_oResult.UserState;
                ReturnObject l_oReturnObject = l_oReturnObjects.First();
                MessageBoxChildWindow L_oMessage = null;
                if (l_oReturnObject.IsValid == true)
                {
                    long caseSwitch = l_iStateId;
                    switch (caseSwitch)
                    {
                        case (int)StateDoc.Validated:
                            L_oMessage = new MessageBoxChildWindow(String.Empty, m_sMsgValidateOK, MessageBoxButtons.Ok, MessageBoxIcon.Information);
                            L_oMessage.Show();
                            break;
                        case (int)StateDoc.Rejected:
                            L_oMessage = new MessageBoxChildWindow(String.Empty, m_sMsgRejectOK, MessageBoxButtons.Ok, MessageBoxIcon.Information);
                            L_oMessage.Show();
                            break;
                        case (int)StateDoc.Indexed:
                            L_oMessage = new MessageBoxChildWindow(String.Empty, m_sMsgIndexOK, MessageBoxButtons.Ok, MessageBoxIcon.Information);
                            L_oMessage.Show();
                            break;
                        case (int)StateDoc.Tranfered:
                            L_oMessage = new MessageBoxChildWindow(String.Empty, m_sMsgTransferOK, MessageBoxButtons.Ok, MessageBoxIcon.Information);
                            L_oMessage.Show();
                            break;
                        case (int)StateDoc.Remind:
                            L_oMessage = new MessageBoxChildWindow(String.Empty, m_sMsgRemindOK, MessageBoxButtons.Ok, MessageBoxIcon.Information);
                            L_oMessage.Show();
                            break;
                    }
                }
                else
                {
                    L_oMessage = new MessageBoxChildWindow(String.Empty, "Echec de l'action: " + l_oReturnObject.ErrorMessage, MessageBoxButtons.Ok, MessageBoxIcon.Error);
                    L_oMessage.Show();
                }

                updateStateHistory();

                OnDataHasChanged();
            }
            else
            {
                throw new Exception("No List of Document Entity retrieved");
            }
        }

        /// <summary>
        /// Handles the ActivateListMode event of the m_oListVignetteSearch control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void m_oListVignetteSearch_ActivateListMode(object sender, EventArgs e)
        {
            m_oViewerControl.Visibility = System.Windows.Visibility.Collapsed;
            m_oListVignetteSearch.Desactivate();

            DisplayMode = SelectModeDocument.List;

            UpdateListDocumentFromSelectedItem();

            ManageToolbarAndContextMenu();

            m_oListViewer.Images = m_oListVignetteSearch.ListItemSource;
            m_oListViewer.Visibility = System.Windows.Visibility.Visible;
        }

        /// <summary>
        /// Event called by the IHM to do a new indexation of an existing document.
        /// This method show the FlowIndexPanel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonIndexer_Click(object sender, RoutedEventArgs e)
        {
            FilterByNonIndexedDocument();
            List<Document> documentsToIndex = new List<Document>();

            if (DisplayMode == SelectModeDocument.Viewer)
            {
                documentsToIndex.Add(CurrentDocument);
            }
            else
            {
                documentsToIndex.AddRange(m_oListVignetteSearch.GetListDocumentFromSelectedThumbnails());
            }

            flowIndexPanel = new FlowIndexPanel(documentsToIndex);
            if (InfoGrid.Children[InfoGrid.Children.Count - 1].GetType() == typeof(FlowIndexPanel))
            {
                InfoGrid.Children.RemoveAt(InfoGrid.Children.Count - 1);
            }

            flowIndexPanel.HorizontalAlignment = HorizontalAlignment.Stretch;
            flowIndexPanel.VerticalAlignment = VerticalAlignment.Stretch;
            flowIndexPanel.CancelClickEvent += flowIndexPanel_CancelClickEvent;
            flowIndexPanel.ValidateClickEvent += flowIndexPanel_ValidateClickEvent;

            foreach (UIElement L_oUIelement in InfoGrid.Children)
            {
                L_oUIelement.Visibility = Visibility.Collapsed;
            }

            Grid.SetRowSpan(flowIndexPanel, 6);
            InfoGrid.Children.Add(flowIndexPanel);
        }

        /// <summary>
        /// Filter document list by non indexed files
        /// </summary>
        public void FilterByNonIndexedDocument()
        {
            BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
            var query = l_oBEDomainContext.GetDocumentByGroupMessageFlowQuery(m_Message.GroupId, m_Message.Identifier, (int)StateDoc.Indexed);
            l_oBEDomainContext.Load(query, OnGetDocumentByGroupMessageFlowQuery, m_Message);
        }

        public void OnGetDocumentByGroupMessageFlowQuery(LoadOperation<Document> result)
        {
            List<Document> l_sDocumentList = new List<Document>(result.Entities);
            if (l_sDocumentList != null && l_sDocumentList.Count > 0)
            {
                foreach (Document l_oDoc in l_sDocumentList)
                {
                    Document l_oDocToDelete = m_sDocumentList.Where(id => id.Identifier == l_oDoc.Identifier).FirstOrDefault();
                    m_sDocumentList.Remove(l_oDocToDelete);
                }


                if (m_sDocumentList != null && m_sDocumentList.Count > 0)
                {
                    CurrentDocument = m_sDocumentList.First();

                    m_sDocuments = new List<string>();
                    m_sDocumentIdList = new List<long>();
                    foreach (Document l_oDoc in m_sDocumentList)
                    {
                        string l_sFullPath = System.IO.Path.Combine(l_oDoc.RelativePath, l_oDoc.ImageName);
                        m_sDocuments.Add(l_sFullPath);
                        m_sDocumentIdList.Add(l_oDoc.Identifier);

                    }

                    if (m_oViewerControl == null)
                    {
                        InitListThumbnailsAndViewerControl(m_sDocumentList);
                    }
                    else
                    {
                        m_oViewerControl.ListDocument = m_sDocumentList;
                        m_oViewerControl.ListAllDocFileName = m_sDocuments;
                        m_oListVignetteSearch.ListDocument = m_sDocumentList;
                        if (m_sDocumentList != null && m_sDocumentList.Count > 0)
                        {
                            flowIndexPanel.m_oListSelectedFilename = new List<Document>();
                            flowIndexPanel.m_oListSelectedFilename.Add(m_sDocumentList[0]);
                        }
                    }
                }
                else
                {
                    InfoGrid.Children.RemoveAt(InfoGrid.Children.Count - 1);
                    foreach (UIElement L_oUIelement in InfoGrid.Children)
                    {
                        L_oUIelement.Visibility = Visibility.Visible;
                    }
                    LoadMessageFlowDocument();
                    buttonIndexer.IsEnabled = false;
                    MessageBoxChildWindow L_oMessage = new MessageBoxChildWindow(String.Empty, "Tous les doucments ont été indexés.", MessageBoxButtons.Ok, MessageBoxIcon.Information);
                    L_oMessage.Show();
                }

            }

        }

        /// <summary>
        /// Event called by the IHM to reject an existing document.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonRefuser_Click(object sender, RoutedEventArgs e)
        {
            CommentChildWindow l_oRejectComment = new CommentChildWindow();
            l_oRejectComment.Header = Resx.GetLabel(ResxFlowPage.REFUSE);
            l_oRejectComment.Closed += new EventHandler<WindowClosedEventArgs>(l_oRejectComment_Closed);
            l_oRejectComment.ShowDialog();
        }

        private void buttonRelancer_Click(object sender, RoutedEventArgs e)
        {
            RemindWindow l_oRemindWindow = new RemindWindow(m_sDocumentList, m_Message);
            l_oRemindWindow.Closed += new EventHandler<WindowClosedEventArgs>(l_oRemindWindow_Closed);
            l_oRemindWindow.ShowDialog();
        }

        /// <summary>
        /// Event called by the IHM to do transfert an existing document.
        /// This method show the VentilatePage
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonTransferer_Click(object sender, RoutedEventArgs e)
        {
            User l_oUser = GlobalWebContext.CurrentUser;
            List<long> l_oDocumentListToVentil = new List<long>();
            foreach (Document l_oDoc in m_sDocumentList)
            {
                l_oDocumentListToVentil.Add(l_oDoc.Identifier);
            }
            VentilateWindow l_oVentilWindow = new VentilateWindow(l_oDocumentListToVentil, 0, l_oUser.UserId, m_Message.Objet);
            l_oVentilWindow.Closed += new EventHandler<WindowClosedEventArgs>(l_oVentilWindow_Closed);
            l_oVentilWindow.ShowDialog();
        }

        /// <summary>
        /// Event called by the IHM to validate an existing document.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonValider_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxChildWindow L_oMessageToValidate = new MessageBoxChildWindow(String.Empty, m_sMsgToValidate, MessageBoxButtons.OkCancel, MessageBoxIcon.Information);
            L_oMessageToValidate.Show();
            L_oMessageToValidate.Closed += (s, ev) =>
            {
                if (L_oMessageToValidate.Result == MessageBoxResult.OK)
                {
                    BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
                    var query = l_oBEDomainContext.UpdateStateDocListQuery(m_sDocumentIdList, (int)StateDoc.Validated, m_Message.Identifier, m_oGroupIdList, String.Empty, m_Message.SendAlertByEmail);
                    l_oBEDomainContext.Load(query, OnUpdateStateDocListQueryCallback, (int)StateDoc.Validated);
                }
            };
        }

        /// <summary>
        /// This method fill all page component at startup. It is called by the constructor;
        /// </summary>
        /// <param name="P_cMsg"></param>
        private void FillPageComponents(MessageFlowDisp P_cMsg)
        {
            //Add the groupid into a list to call the UpdateStateDocList query
            m_oGroupIdList = new List<long>();
            m_oGroupIdList.Add(P_cMsg.GroupId);

            LabelValueFrom.Text = P_cMsg.Emetteur.FirstName + " " + P_cMsg.Emetteur.LastName;
            LabelValueObject.Text = P_cMsg.Objet;
            LabelValueTo.Text = P_cMsg.DestinataireList;
            FlowMemo.Text = P_cMsg.Memo;

            if (m_sDocumentList != null && m_sDocumentList.Count > 0)
            {
                string l_sInfoDocFormat = "{0}:\r{1}\r";
                //foreach (Document l_oDoc in m_sDocumentList)
                //{
                Document l_oDoc = m_sDocumentList[0];
                if (l_oDoc != null && !string.Empty.Equals(l_oDoc.Author))
                {
                    DocumentIndex.Text += String.Format(l_sInfoDocFormat, m_sLabelAuthor, l_oDoc.Author);
                }
                if (l_oDoc.Note != null && !string.Empty.Equals(l_oDoc.Note))
                {
                    DocumentIndex.Text += String.Format(l_sInfoDocFormat, m_sLabelNote, l_oDoc.Note);
                }
                if (l_oDoc.PhotoCredit != null && !string.Empty.Equals(l_oDoc.PhotoCredit))
                {
                    DocumentIndex.Text += String.Format(l_sInfoDocFormat, m_sLabelNumChrono, l_oDoc.PhotoCredit);
                }
                //}
            }
        }

        /// <summary>
        /// Initialize the IHM components with the correct language
        /// </summary>
        private void InitLabel()
        {
            buttonValider.Content = Resx.GetLabel(ResxFlowPage.VALIDATE);
            buttonRefuser.Content = Resx.GetLabel(ResxFlowPage.REFUSE);
            buttonTransferer.Content = Resx.GetLabel(ResxFlowPage.TRANSFER);
            buttonIndexer.Content = Resx.GetLabel(ResxFlowPage.INDEX);
            LabelFrom.Content = Resx.GetLabel(ResxFlowPage.FROM);
            LabelObject.Content = Resx.GetLabel(ResxFlowPage.OBJECT);
            LabelTo.Content = Resx.GetLabel(ResxFlowPage.TO);
            LabelStateHistory.Content = Resx.GetLabel(ResxFlowPage.STATEHISTORY);
            LabelIndex.Content = Resx.GetLabel(ResxFlowPage.INDEXHISTORY);
            m_sLabelNoHistory = Resx.GetLabel(ResxFlowPage.NOSTATEHISTORY); 
            m_sMsgIndexOK = Resx.GetLabel(ResxFlowPage.MSG_INDEX_OK); 
            m_sMsgValidateOK = Resx.GetLabel(ResxFlowPage.MSG_VALIDATE_OK);
            m_sMsgToValidate = Resx.GetLabel(ResxFlowPage.MESSAGE_TO_VALIDATE);
            m_sMsgTransferOK = Resx.GetLabel(ResxFlowPage.MSG_TRANSFER_OK);
            m_sMsgRejectOK = Resx.GetLabel(ResxFlowPage.MSG_REJECT_OK); 
            m_sMsgRemindOK = Resx.GetLabel(ResxFlowPage.MSG_REMIND_OK); 
            LabelMemo.Content = Resx.GetLabel(ResxFlowPage.MEMO); 
            m_sMsgIndexedBy = Resx.GetLabel(ResxFlowStateHistory.MSG_INDEXEDBY);
            m_sMsgValidatedBy = Resx.GetLabel(ResxFlowStateHistory.MSG_VALIDATEDBY); 
            m_sMsgTransferedBy = Resx.GetLabel(ResxFlowStateHistory.MSG_TRANSFEREDBY);
            m_sMsgRejectedBy = Resx.GetLabel(ResxFlowStateHistory.MSG_REJECTEDBY); 
            m_sMsgRemindBy = Resx.GetLabel(ResxFlowStateHistory.MSG_REMINDBY); 
            m_sMsgReadBy = Resx.GetLabel(ResxFlowStateHistory.MSG_READBY); 
            m_sLabelNote = Resx.GetLabel(ResxInfosDocument.NOTE); 
            m_sLabelAuthor = Resx.GetLabel(ResxInfosDocument.AUTHOR); 
            m_sLabelNumChrono = Resx.GetLabel(ResxInfosDocument.PHOTO_CREDIT); 
            buttonRelancer.Content = Resx.GetLabel(ResxFlowPage.REMIND); 
            m_oSplashScreen.Message = Resx.GetLabel(ResxCommon.SPLASHSCREEN_MESSAGE);
        }

        /// <summary>
        /// Init Thumbnails and viewer
        /// </summary>
        /// <param name="p_oListDocument"></param>
        private void InitListThumbnailsAndViewerControl(List<Document> p_oListDocument)
        {
            m_oViewerControl = new UCViewer(p_oListDocument, AppDisplayMode.Flow);
            m_oViewerControl.Name = "ViewerControl";
            m_oViewerControl.HorizontalAlignment = HorizontalAlignment.Stretch;
            m_oViewerControl.VerticalAlignment = VerticalAlignment.Stretch;
            m_oViewerControl.SetValue(Grid.RowProperty, 0);
            m_oViewerControl.SetValue(Grid.ColumnProperty, 0);

            m_oViewerControl.ActivateListMode += m_oListVignetteSearch_ActivateListMode;
            m_oViewerControl.ActivateThumbnailMode += ViewerControl_ActivateThumbnailMode;
            m_oViewerControl.DisplayCompleted += m_oViewerControl_DisplayCompleted;
            m_oViewerControl.InitialisationCompleted += m_oViewerControl_InitialisationCompleted;

            ViewerControlPanel.Children.Add(m_oViewerControl);
            m_oViewerControl.DeactivateKeyPress();

            DisplayMode = SelectModeDocument.Viewer;
            m_oViewerControl.Visibility = Visibility.Visible;
        }

        private void ListVignetteSearch_ItemsLoaded(object sender, DocumentSelectedEventArgs e)
        {
            if (DisplayMode == SelectModeDocument.Viewer)
            {
                LoadDocumentInViewer(m_oCurrentDocument);
            }
            else
            {
                m_oListVignetteSearch.Activate(m_oViewerControl.SelectedDocumentIndex);
            }
            m_oListViewer.Images = e.ListAllRioImagesSearch;
        }

        void ListVignetteSearch_ItemsSelectedDocument(object sender, DocumentSelectedEventArgs args)
        {
            if ((args.p_oListDocument != null) && (args.p_oListDocument.Count > 0))
            {
                if (args.p_oListDocument.Count == 1)
                {
                    //We selecte the document to display its data
                    CurrentDocument = args.p_oListDocument[0];
                    if (flowIndexPanel != null)
                    {
                        flowIndexPanel.m_oListSelectedFilename = args.p_oListDocument;
                    }

                }
                else
                {
                    // we have selected more of one document so we can't display data document
                    CurrentDocument = null;
                    if (flowIndexPanel != null)
                    {
                        if (args.p_oListDocument != null && args.p_oListDocument.Count > 0)
                        {
                            flowIndexPanel.m_oListSelectedFilename = args.p_oListDocument;
                        }
                        else
                        {
                            flowIndexPanel.m_oListSelectedFilename.Clear();
                        }
                    }
                }
            }
            else
            {
                //Nothing document are selected, so we remove displayed document data by puting null value
                CurrentDocument = null;

                //m_oListSelectedDocumentFromThumbnails = null;
            }
        }

        private void ListVignette_ActivateViewerMode(object sender, EventArgs e)
        {
            DisplayMode = SelectModeDocument.Viewer;

            m_oListVignetteSearch.Desactivate();
            m_oViewerControl.Visibility = Visibility.Visible;
            m_oListViewer.Visibility = System.Windows.Visibility.Collapsed;

            UpdateListDocumentFromSelectedItem();
        }

        /// <summary>
        /// Raise when an item is selected in the ListVignette by a double click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ListVignette_ItemSelectedToDisplay(object sender, EventArgs e)
        {
            m_oViewerControl.LoadImageFromDocument(GlobalWebContext.CurrentUser.UserId, m_oListVignetteSearch.ListAllDocFileName, ((System.Windows.Controls.ListBox)m_oListVignetteSearch.FindName("ListBoxVignette")).SelectedIndex, false);
            m_oViewerControl.Visibility = System.Windows.Visibility.Visible;
            m_oListVignetteSearch.Visibility = System.Windows.Visibility.Collapsed;
            m_oListViewer.Visibility = System.Windows.Visibility.Collapsed;
        }

        void ListVignette_ItemsSelectedFileName(List<string> p_oListFileName)
        {
            //m_oControlImportPanel.m_oListSelectedFilename = p_oListFileName;
        }

        void ListVignette_ItemsSelectedToDisplay(object sender, DocumentSelectedEventArgs args)
        {
            m_oViewerControl.LoadImageFromDocument(GlobalWebContext.CurrentUser.UserId, m_oListVignetteSearch.GetListFullNameAllDocument(), (sender as UCViewerCore).SelectedDocumentIndex, true);
            m_oViewerControl.Visibility = System.Windows.Visibility.Visible;
            m_oListVignetteSearch.Visibility = System.Windows.Visibility.Collapsed;
            m_oListViewer.Visibility = System.Windows.Visibility.Collapsed;
        }

        void ListVignette_RefreshThumbnails(object sender, EventArgs e)
        {
            m_oViewerControl.LoadImageFromDocument(GlobalWebContext.CurrentUser.UserId, m_oListVignetteSearch.ListAllDocFileName, 0, false);
            m_oListVignetteSearch.RefreshThumbnails -= ListVignette_RefreshThumbnails;
        }

        /// <summary>
        /// Find the document's imae to display it
        /// </summary>
        /// <param name="P_oDocument"></param>
        private void LoadDocumentInViewer(Document P_oDocument)
        {
            string L_szFileNameDoc;
            try
            {
                if (P_oDocument != null)
                {
                    List<string> L_oListFullnameAllDocument = m_sDocuments;
                    if ((L_oListFullnameAllDocument != null) && (L_oListFullnameAllDocument.Count > 0))
                    {
                        for (int i = 0; i < L_oListFullnameAllDocument.Count; i++)
                        {
                            L_szFileNameDoc = Path.GetFileNameWithoutExtension(L_oListFullnameAllDocument[i]);
                            if (L_szFileNameDoc.Equals(Path.GetFileNameWithoutExtension(P_oDocument.ImageName)))
                            {
                                m_oViewerControl.LoadImageFromDocument(GlobalWebContext.CurrentUser.UserId, L_oListFullnameAllDocument, i, true);
                            }
                        }
                    }
                    else
                    {
                        m_oViewerControl.ClearViewer();
                    }
                }
                else
                {
                    m_oViewerControl.ReinitializeViewer();
                }
            }
            catch (Exception ex)
            {
                Logger.Write("EXCEPTION : " + Environment.NewLine + ex, Logger.Level.Error);
            }
        }

        void flowIndexPanel_CancelClickEvent(object sender, EventArgs e)
        {
            InfoGrid.Children.RemoveAt(InfoGrid.Children.Count - 1);
            foreach (UIElement L_oUIelement in InfoGrid.Children)
            {
                L_oUIelement.Visibility = Visibility.Visible;
            }
        }

        /// <summary>
        ///  This event is called when the user close the FlowIndexPanel popup 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void flowIndexPanel_Closed(object sender, EventArgs e)
        {
            //FlowIndexPanel L_oFilterWindow = (FlowIndexPanel)sender;
            //if (L_oFilterWindow.DialogResult == true)
            //{
            //    BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
            //    var query = l_oBEDomainContext.UpdateStateDocListQuery(m_sDocumentIdList, (int)StateDoc.Indexed, m_Message.Identifier, m_oGroupIdList, String.Empty, m_Message.SendAlertByEmail);
            //    l_oBEDomainContext.Load(query, OnUpdateStateDocListQueryCallback, (int)StateDoc.Indexed);
            //}
        }

        void flowIndexPanel_ValidateClickEvent(object sender, EventArgs e)
        {
            BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
            var query = l_oBEDomainContext.UpdateStateDocListQuery(m_sDocumentIdList, (int)StateDoc.Indexed, m_Message.Identifier, m_oGroupIdList, String.Empty, m_Message.SendAlertByEmail);
            l_oBEDomainContext.Load(query, OnUpdateStateDocListQueryCallback, (int)StateDoc.Indexed);
        }

        void l_oRejectComment_Closed(object sender, EventArgs e)
        {
            CommentChildWindow l_oRejectComment = (CommentChildWindow)sender;
            if (l_oRejectComment.DialogResult == true)
            {
                BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
                var query = l_oBEDomainContext.UpdateStateDocListQuery(m_sDocumentIdList, (int)StateDoc.Rejected, m_Message.Identifier, m_oGroupIdList, l_oRejectComment.Comment, m_Message.SendAlertByEmail);
                l_oBEDomainContext.Load(query, OnUpdateStateDocListQueryCallback, (int)StateDoc.Rejected);
            }
        }

        void l_oRemindWindow_Closed(object sender, EventArgs e)
        {
            RemindWindow l_oRemindWindow = (RemindWindow)sender;
            if (l_oRemindWindow.DialogResult == true)
            {
                List<long> l_oGroupIdList = new List<long>();
                foreach (Group l_oGroup in l_oRemindWindow.GetMailTo)
                {
                    l_oGroupIdList.Add(l_oGroup.Identifier);
                }

                BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
                var query = l_oBEDomainContext.AddMessageFlowReminderQuery(m_Message.Identifier, l_oGroupIdList);
                l_oBEDomainContext.Load(query, OnAddMessageFlowReminderQuery, null);
            }
        }

        /// <summary>
        /// This event is called when the user close the transfer page "VentilatePage"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void l_oVentilWindow_Closed(object sender, EventArgs e)
        {
            VentilateWindow l_oVentilWindow = (VentilateWindow)sender;
            if (m_Message.GroupId != 0 && l_oVentilWindow.DialogResult == true)
            {
                BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
                var query = l_oBEDomainContext.UpdateStateDocListQuery(m_sDocumentIdList, (int)StateDoc.Tranfered, m_Message.Identifier, m_oGroupIdList, l_oVentilWindow.Destination, m_Message.SendAlertByEmail);
                l_oBEDomainContext.Load(query, OnUpdateStateDocListQueryCallback, (int)StateDoc.Tranfered);
            }
            OnDataHasChanged();
        }

        /// <summary>
        /// Close SplashScreen when the image have been displayed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void m_oViewerControl_DisplayCompleted(object sender, EventArgs e)
        {
            ManageToolbarAndContextMenu();

            Rio.Framework.Pages.ModalControls.ModalDialogController.Close();
            m_oSplashScreen.Close();
        }

        /// <summary>
        /// Init Label when ParamaterStorage have been initialized
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void m_oViewerControl_InitialisationCompleted(object sender, EventArgs e)
        {
            LoadDocumentInViewer(m_oCurrentDocument);

            m_oListVignetteSearch = new ListVignetteSearch(m_sDocumentList, null, false);
            m_oListVignetteSearch.Name = "ListVignetteSearchControl";
            m_oListVignetteSearch.HorizontalAlignment = HorizontalAlignment.Stretch;
            m_oListVignetteSearch.VerticalAlignment = VerticalAlignment.Stretch;
            m_oListVignetteSearch.SetValue(Grid.RowProperty, 0);
            m_oListVignetteSearch.SetValue(Grid.ColumnProperty, 0);

            ViewerControlPanel.Children.Add(m_oListVignetteSearch);

            m_oListVignetteSearch.Desactivate();
            m_oListVignetteSearch.DeactivateKeyPress();

            m_oListVignetteSearch.ActivateListMode += m_oListVignetteSearch_ActivateListMode;
            m_oListVignetteSearch.ActivateViewerMode += ListVignette_ActivateViewerMode;
            m_oListVignetteSearch.ItemsSelectedToDisplay += ListVignette_ItemsSelectedToDisplay;
            m_oListVignetteSearch.ItemsSelectedDocument += ListVignetteSearch_ItemsSelectedDocument;
            m_oListVignetteSearch.ItemsLoaded += ListVignetteSearch_ItemsLoaded;

            FillPageComponents(m_Message);

            /*
             * ListViewer
             */

            m_oListViewer = new ListViewer(AppDisplayMode.Flow)
            {
                Name = "ListViewer",
                Visibility = System.Windows.Visibility.Collapsed
            };

            m_oListViewer.SetValue(Grid.RowProperty, 0);
            m_oListViewer.SetValue(Grid.ColumnProperty, 0);

            ViewerControlPanel.Children.Add(m_oListViewer);

            m_oListViewer.ActivateThumbnailMode += ViewerControl_ActivateThumbnailMode;
            m_oListViewer.ActivateViewerMode += ListVignette_ActivateViewerMode;
            m_oListViewer.ItemsSelectedToDisplay += ListVignette_ItemsSelectedToDisplay;

            //Set toolbar privileges
            //((RadMenuItem)m_oListViewer.FindName("ItemMergePdf")).Visibility = System.Windows.Visibility.Collapsed;
            //((RadToolBarSeparator)m_oListViewer.FindName("radToolBarSeparator5")).Visibility = System.Windows.Visibility.Collapsed;
            //((RadMenuItem)m_oListViewer.FindName("ItemMergePdfContextMenu")).Visibility = System.Windows.Visibility.Collapsed;
            //((RadMenuItem)m_oListViewer.FindName("contextSeparator1")).Visibility = System.Windows.Visibility.Collapsed;
            //((RadMenuItem)m_oListViewer.FindName("contextSeparator2")).Visibility = System.Windows.Visibility.Collapsed;

        }

        /// <summary>
        /// Email query callback
        /// </summary>
        /// <param name="result"></param>
        private void OnAddMessageFlowReminderQuery(LoadOperation<ReturnBoolean> result)
        {
            if (result.Error != null)
            {
                Logger.Write("EXCEPTION : " + Environment.NewLine + result.Error, Logger.Level.Error);
            }
        }

        private void SetAsRead()
        {
            if (m_Message.GroupId != 0)
            {

                List<long> l_oGroupIdList = new List<long>();
                l_oGroupIdList.Add(m_Message.GroupId);
                BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
                var query = l_oBEDomainContext.UpdateStateDocListQuery(m_sDocumentIdList, (int)StateDoc.Read, m_Message.Identifier, l_oGroupIdList, String.Empty, m_Message.SendAlertByEmail);
                l_oBEDomainContext.Load(query, OnUpdateStateDocListQueryCallback, (int)StateDoc.Read);

                var query2 = l_oBEDomainContext.GetHistoryByGroupMessageFlowQuery(m_Message.GroupId, m_sDocumentList[0].Identifier, m_Message.Identifier);
                l_oBEDomainContext.Load(query2, OnHistoryByGroupMessageFlowQuery, null);
                buttonRelancer.Visibility = System.Windows.Visibility.Collapsed;

            }
            else
            {
                BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
                var query = l_oBEDomainContext.UpdateMessageFlowLastReadDateQuery(m_Message.Identifier);
                l_oBEDomainContext.Load(query, OnUpdateMessageFlowLastReadDateQuery, m_Message);

                buttonValider.Visibility = System.Windows.Visibility.Collapsed;
                buttonRefuser.Visibility = System.Windows.Visibility.Collapsed;
                buttonIndexer.Visibility = System.Windows.Visibility.Collapsed;
                buttonRelancer.Visibility = System.Windows.Visibility.Visible;

                var query2 = l_oBEDomainContext.GetHistoryByUserMessageFlowQuery(m_Message.Emetteur.UserId, m_sDocumentList[0].Identifier, m_Message.Identifier);
                l_oBEDomainContext.Load(query2, OnHistoryByGroupMessageFlowQuery, null);
            }
        }

        private void UpdateListDocumentFromSelectedItem()
        {
            #region Update CurrentDocument
            if (m_sDocuments != null && m_sDocuments.Count > 0)
            {
                if ((CurrentDocument == null) || (m_sDocumentList.Contains(CurrentDocument) == false))
                    CurrentDocument = m_sDocumentList[0];
            }
            else
            {
                CurrentDocument = null;
            }
            #endregion

            #region refresh the activate display mode
            if (DisplayMode == SelectModeDocument.Viewer)
            {
                if (m_sDocumentList != null)
                {
                    m_oViewerControl.ListDocument = m_sDocumentList;
                    m_oViewerControl.ListAllDocFileName = m_sDocuments;
                }
                LoadDocumentInViewer(CurrentDocument);
            }

            //Not necessary to reload thumbnails if the number of documents are identical:
            //      Reason: No way to alter the document(rotate...etc). Add, delete, change item will change the number of documents anyway
            if ((m_oListVignetteSearch.ListBoxItems.Count == 0 && m_oListVignetteSearch.ListDocument.Count > 0)
                || (m_oListVignetteSearch.ListDocument.Count != m_sDocumentList.Count))
            {
                m_oListVignetteSearch.ListDocument = m_sDocumentList;



                m_oListViewer.ListDocument = m_sDocumentList;
            }
            #endregion
        }

        /// <summary>
        /// This method update the document state history
        /// </summary>
        private void updateStateHistory()
        {
            if (m_Message.GroupId != 0)
            {
                BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
                var query = l_oBEDomainContext.GetHistoryByGroupMessageFlowQuery(m_Message.GroupId, m_sDocumentList[0].Identifier, m_Message.Identifier);
                l_oBEDomainContext.Load(query, OnHistoryByGroupMessageFlowQuery, null);
            }
            else
            {
                BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
                var query = l_oBEDomainContext.GetHistoryByUserMessageFlowQuery(m_Message.Emetteur.UserId, m_sDocumentList[0].Identifier, m_Message.Identifier);
                l_oBEDomainContext.Load(query, OnHistoryByGroupMessageFlowQuery, null);
            }
        }

        void ViewerControl_ActivateThumbnailMode(object sender, EventArgs e)
        {
            DisplayMode = SelectModeDocument.Thumbnail;

            m_oViewerControl.Visibility = Visibility.Collapsed;
            m_oViewerControl.ClearViewer();

            UpdateListDocumentFromSelectedItem();

            ManageToolbarAndContextMenu();

            m_oListVignetteSearch.Visibility = Visibility.Visible;
            m_oListViewer.Visibility = System.Windows.Visibility.Collapsed;
        }

        void ViewerControl_ItemsSelectedFileName(List<string> p_oListFileName)
        {
            //m_oControlImportPanel.m_oListSelectedFilename = p_oListFileName;
        }

        #endregion Methods
    }
}